package  
{
	import org.flixel.*;

	public class Player extends FlxSprite 
	{
		[Embed(source = "../art/robot.png")] protected var gfxRobot:Class;
		
		private static const GRAVITY:Number = 420;
		private static const JUMP_SPEED:Number = 225;
		private static const RUN_SPEED:Number = 80;
		
		private static const BULLET_SPEED:Number = 200;
		private static const BULLET_RANDOMNESS:Number = 40;
		private static const GUN_DELAY:Number = 0.05;
		protected var coolDown:Number;
		
		public var lives:Number = 3;
		
		public var bullets:Array;
		private var bulletIndex:Number = 0;
		
		public function Player(_x:Number, _y:Number) 
		{
			super(_x, _y);
			
			loadGraphic(gfxRobot, true, true, 8, 16);
			addAnimation("idle", [0]);
			addAnimation("walking", [1, 0, 2, 0], 6, true);
			addAnimation("jumping", [3]);
			play("walking");
			
			drag.x = RUN_SPEED * 8;
			acceleration.y = GRAVITY;
			maxVelocity.x = RUN_SPEED;
			maxVelocity.y = JUMP_SPEED;
			coolDown = GUN_DELAY;
			
			bullets = new Array();
		}
		
		override public function update():void {
			acceleration.x = 0;
			
			coolDown += FlxG.elapsed;
			
			if (FlxG.keys.justPressed("UP") || FlxG.keys.justPressed("W")) {
				if (!velocity.y) {
					velocity.y = -JUMP_SPEED;
				}
			}
			
			if (FlxG.keys.A || FlxG.keys.LEFT) {
				facing = LEFT;
				acceleration.x = -drag.x;
			}
			
			if (FlxG.keys.D || FlxG.keys.RIGHT) {
				facing = RIGHT;
				acceleration.x = drag.x;
			}
			
			if (FlxG.keys.SPACE || FlxG.keys.X) {
				if (coolDown >= GUN_DELAY)
					ShootBullet();
			}
			
			if (velocity.y != 0){
				play("jumping");
			}else if (velocity.x != 0) {
				play("walking");
			}else {
				play("idle");
			}
			
			super.update();
		}
		
		public function ShootBullet():void {
			if (facing == LEFT) {
				bullets[bulletIndex].Shoot(x, y, -BULLET_SPEED, 0, BULLET_RANDOMNESS);
			}else {
				bullets[bulletIndex].Shoot(x, y, BULLET_SPEED, 0, BULLET_RANDOMNESS);
			}
			coolDown = 0;
			
			if (bulletIndex == bullets.length - 1) {
				bulletIndex = 0;
			}else {
				bulletIndex++;
			}
		}
		
		override public function kill():void {
			super.kill();
		}
		
		public function hitObject(_damage:Number):void {
			lives -= _damage;
			
			FlxG.quake.start(0.005, 0.35);
			FlxG.flash.start(0xffDB3624, 0.35);
			
			if (lives <= 0) {
				kill();
			}
		}
	}
}